/** @author wanghua
		@date	 2017-9-13
*/

window._alert = alert;//保留原生的alert
window.alert = myalert;
/**用于替换alert*/
function myalert(content, title,  icon, callback){
	$("body").focus();
	if(top.dkDialog){//优先使用顶层窗口的alert
		top.dkDialog.alert(content, title,  icon, callback);
	}else if(dkDialog){
		dkDialog.alert(content, title,  icon, callback);
	}else{
		_alert(content, title);
	}
}

var dkDialog = {

	alert : function(content, title,  icon, callback){
		if(!title) title = '提示';


		var index = layer.open({
			title : title,
			content: content,
			icon : icon || 0,
			yes: function(index, layero){
				layer.close(index); //如果设定了yes回调，需进行手工关闭
				if(callback)callback();
			},
			success: function(layero, index){ //层弹出后的成功回调方法
				var self = this;
				this.enterEsc = function(event){
					console.log("key down");
					if(event.keyCode === 13 || event.keyCode === 32){//回车键 空格键
						layer.close(index);
						return false; //阻止系统默认回车事件
					}
				};
				$(document).on('keydown', this.enterEsc);   //监听键盘事件，关闭层
				$(".layui-layer-btn").attr("tabindex",1);	 //div 设置tabindex，才能获取焦点
				$(".layui-layer-btn").focus(); //by wanghua 防止按enter键时，继续触发引起弹框的操作（比如超链接，因为alert是超链接继续持有焦点，enter键会继续触发超链接的点击事件）。
			},
			end: function(){//无论是确认还是取消，只要层被销毁了，end都会执行
				$(document).off('keydown', this.enterEsc);  //解除键盘关闭事件
			}
		});
	},


	dialogCache : [],//缓存所有打开的dkDialog。	此处定义的变量，所有实例对象能够读写同一数据
	openDialog : function(setting){
		var dialog = {};
		var defaultOptions = {
			resize:true
		};

		var options = $.extend(defaultOptions, setting);

		var layer = layui.layer;
		/* {id,title,url,modal,width,height,shade,onMinized,onMaxized,onRestore,onClosed,left,top,resize:false} */
		/*left top 为空时，窗口默认居中*/
		dialog.open = function(){
			var that = this;

			var unshowMask = options.shade === false || options.modal === false;//不显示遮罩
			var shade = options.shade || 0.6;
			if(unshowMask) shade = false;
			var layerOptions = options;
			layerOptions.area = [(options.width || 600) + 'px', (options.height || 480) + 'px'];
			layerOptions.shade = shade;
			layerOptions.title = layerOptions.title || ' ';
			layerOptions.content = layerOptions.content || layerOptions.url;
			layerOptions.type = 2;
			if(!layerOptions.min)layerOptions.min = function(){that.doEvent('onMinized')};
			if(!layerOptions.max)layerOptions.max = function(){that.doEvent('onMaxized')};
			if(!layerOptions.restore)layerOptions.restore = function(){that.doEvent('onRestore')};
			if(!layerOptions.end)layerOptions.end = function(layerId){//窗口关闭时移除缓存的dialog
				for(var i=0; i<dkDialog.dialogCache.length; ++i){
					var dlg = dkDialog.dialogCache[i];
					if(dlg && dlg.layerId == layerId){
						dkDialog.dialogCache[i] = null;
						delete dkDialog.dialogCache[i];
						break;
					}
				}
				if(options.onClosed){
					options.onClosed(options.customCloseEvent);
				}
				if(options.Closed){
					options.Closed(options.customCloseEvent);
				}

				if(that.onClosed)that.onClosed(options.customCloseEvent);
				if(that.Closed)that.Closed(options.customCloseEvent);

				that.doEvent('Closed',options.customCloseEvent);
			};

			layerOptions.cancel = function(){
				var result1 = that.doEvent('Close');//兼容之前ligerDialog的事件
				var result2 = that.doEvent('onCancel');
				if(result1 === false || result2 === false)return false;
				else return true;
			};

			var layerId = layer.open(layerOptions);
			this.layerId = layerId;
			this.id = options.id;

			this.iframeId = "layui-layer-iframe"+ layerId;
			
			var childframeId = 'layui-layer-iframe' + layerId;
			var childframe = document.getElementById(childframeId)
//			if(childframe){
//				childframe.contentWindow.closeDialog = function(resultType, dataId){//给窗口设置close函数，用于关闭弹出框  //bug by wanghua:iframe刷新后，注入的closeDialog会失效
//					that.close(resultType, dataId);
//				}
//			}

			dkDialog.dialogCache.push(dialog);
		};
		/**同hide*/
		dialog.hidden = function(){
			this.hide();
		};
		/**隐藏窗口*/
		dialog.hide = function(){
			$("#layui-layer"+this.layerId).hide();
			$("#layui-layer-shade"+this.layerId).hide();
		};
		/**恢复显示窗口*/
		dialog.show = function(){
			$("#layui-layer"+this.layerId).show();
			$("#layui-layer-shade"+this.layerId).show();
		};

		dialog.close = function(customCloseEvent){
			options.customCloseEvent = customCloseEvent;//窗口关闭时的事件参数
			layer.close(this.layerId);
		};


		dialog.set = function(name, value){
			options[name] = value;
		};

		dialog.get = function(name){
			return options[name];
		};

		dialog.bind = function(eventName, callback){
			if(!options.events){
				options.events = [];
			}
			options.events.push({name:eventName,callback: callback});
		};

		dialog.doEvent = function(eventName, eventParams){
			if(!options.events)return;
			var events = options.events;
			var result;
			for(var i=0; i<events.length; ++i){
				var item = events[i];
				if(eventName == item.name && item.callback){
					result = item.callback(eventParams);
				}
			}
			return result;
		}

		dialog.open();

		return dialog;
	},

	get : function(id){
		for(var i=0; i<this.dialogCache.length; ++i){
			var dlg = this.dialogCache[i];
			if(dlg && dlg.id == id)return dlg;
		}
	}

};

var loadingLayerIndex = 0;
/**显示loading*/
function dkDialog_showLoading(){
	var layer = layui.layer;
	if(loadingLayerIndex){
		return;
	}else{
		loadingLayerIndex = layer.load(3);
	}
}

/**关闭loading*/
function dkDialog_closeLoading(){
	var layer = layui.layer;
	if(loadingLayerIndex){
		layer.close(loadingLayerIndex);
		loadingLayerIndex = 0;
	}
}

/**全局定义 ajax请求开始的时候显示loading图标*/
//$(document).ajaxStart(function() {
//	dkDialog_showLoading();
//});
//
//$(document).ajaxError(function( event, request, settings ) {
//	dkDialog_closeLoading();
//});
//
//$(document).ajaxStop(function() {
//	dkDialog_closeLoading();
//});
